﻿using System;
using System.Collections.Generic;
using System.Linq;
using VideoSeller.Business.Data;
using VideoSeller.Business.Data.Enums;

namespace VideoSeller.Business.Models
{
	public class WaitModel : Repository<Wait>
	{
		private readonly OnlineContentModel _onlineContentModel;

		public WaitModel(OnlineContentModel onlineContentModel)
		{
			_onlineContentModel = onlineContentModel;
		}

		public void MarkOnlineContent(int onlineContentId, Guid userId, bool remove = false)
		{
			if (remove)
			{
				var item = Table.FirstOrDefault(x => x.OnlineContentId == onlineContentId && x.UserId == userId);

				if (item != null)
				{
					Delete(item);
					return;
				}
			}

			if (!Table.Any(x => x.OnlineContentId == onlineContentId && x.UserId == userId))
			{
				var wait = new Wait
					{
						OnlineContentId = onlineContentId,
						UserId = userId
					};
				Insert(wait);
			}
		}

		public IEnumerable<OnlineContent> GetWantToSee(Guid userId)
		{
			return Table.Where(x => x.UserId == userId && x.OnlineContent.State > -1).Select(x => x.OnlineContent);
		}

		public IEnumerable<OnlineContent> GetWantToSee(Guid userId, OnlineContentType onlineContentType)
		{
			var items = Table.Where(x => x.UserId == userId && x.OnlineContent.State > -1).Select(x => x.OnlineContent);

			switch (onlineContentType)
			{
				case OnlineContentType.Announcement:
					return items.Where(x => !x.Active && x.DownloadUrl == null);
				case OnlineContentType.Online:
					return items.Where(x => x.Active);
				case OnlineContentType.History:
					return items.Where(x => !x.Active && x.DownloadUrl != null);
			}

			return items;
		}

		public bool IsWantToSee(int onlineContentId, Guid userId)
		{
			return Table.FirstOrDefault(x => x.OnlineContentId == onlineContentId && x.UserId == userId) != null;
		}

		public IEnumerable<KeyValuePair<OnlineContent, int>> GetExpectMe(Guid userId)
		{
			return _onlineContentModel.GetAll(userId).Select(x => new KeyValuePair<OnlineContent, int>(x, Table.Count(y => y.OnlineContentId == x.Id)));
		}

		public int GetExpectMe(int onlineContentId)
		{
			return Table.Count(y => y.OnlineContentId == onlineContentId);
		}

		public void DeleteAll(IEnumerable<Wait> items)
		{
			foreach (var item in items)
			{
				var oncat = Table.SingleOrDefault(x => x.Id == item.Id);

				if (oncat != null)
				{
					Table.DeleteOnSubmit(oncat);
				}
			}

			SubmitAllChanges();
		}
	}
}